package Task5;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;

public class ServerThread extends Thread {
    private Socket s;

    public ServerThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
            BufferedReader br = null;
            PrintStream ps = null;
            FileOutputStream fos = null;
            try {
                // 3.使用输入输出流进行通信
                br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //fos = new FileOutputStream("\"/Users/ZiyangZhang/Desktop/CS/java/Module1Task/src/com/lagou/Module4/src/Task3/CopyDir/1.txt\"");
                while (true) {
                    // 实现对客户端发来字符串内容的接收并打印
                    // 当没有数据发来时，下面的方法会形成阻塞
                    String s1 = br.readLine();
                    InetAddress inetAddress = s.getInetAddress();
                    // 当客户端发来的内容为"bye"时，则聊天结束
                    if ("bye".equalsIgnoreCase(s1)) {
                        System.out.println("客户端" + inetAddress + "已下线！");
                        Server.socketArray.remove(s);
                        continue;
                    }
                    for (Socket sk : Server.socketArray
                    ) {
                        ps = new PrintStream(sk.getOutputStream());
                        ps.println("客户端" + inetAddress + "发来的字符串内容是：" + s1);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != ps) {
                    ps.close();
                }
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != s) {
                    try {
                        s.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    }
}
